package com.cswangdao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cswangdao.domain.po.MarketSystem;
import com.cswangdao.domain.vo.MarketMallVo;
import com.cswangdao.mapper.MarketSystemMapper;
import com.cswangdao.service.MallConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class MallConfigServiceImpl implements MallConfigService {


    @Autowired
    private MarketSystemMapper mapper;

    /**
     * @description: 获取商场配置信息
     * @param:
     * @return: com.cswangdao.domain.vo.MarketMallVo
     */
    @Override
    public MarketMallVo getMarketMall() {
        try/*(SqlSession sqlSession = MybatisUtil.getSqlSession(true))*/ {
        //    MarketSystemMapper mapper = sqlSession.getMapper(MarketSystemMapper.class);
            List<MarketSystem> marketMall = mapper.getByPrefix("market_mall");
            MarketMallVo marketMallVo = new MarketMallVo();
            Map<String,String> map = new HashMap<>();
            for (MarketSystem marketSystem : marketMall) {
                map.put(marketSystem.getKeyName(),marketSystem.getKeyValue());
            }
            BeanUtil.fillBeanWithMap(map,marketMallVo,false);
            return marketMallVo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    /** 
     * @description: 修改商场配置信息
     * @param: marketMallVo 
     * @return: boolean 
     */ 
    public boolean updateMarkrtMall(MarketMallVo marketMallVo) {
        try/*(SqlSession sqlSession = MybatisUtil.getSqlSession();) */{
           // MarketSystemMapper mapper = sqlSession.getMapper(MarketSystemMapper.class);
            List<MarketSystem> marketMall = mapper.getByPrefix("market_mall");
            Date addTime = marketMall.get(1).getAddTime();
            mapper.deleteByPrefix("market_mall");
            List<MarketSystem> list = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            Map<String, Object> stringObjectMap = BeanUtil.beanToMap(marketMallVo, map, false, true);
            Set<Map.Entry<String, Object>> entries = stringObjectMap.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                MarketSystem marketSystem = new MarketSystem();
                marketSystem.setUpdateTime(new Date());
                marketSystem.setAddTime(addTime);
                marketSystem.setKeyName(entry.getKey());
                marketSystem.setKeyValue((String) entry.getValue());
                list.add(marketSystem);
            }
            mapper.insertBatch(list);
        //    sqlSession.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
